from django.conf import settings
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
import random
from datetime import datetime
from django.contrib.auth.hashers import check_password,make_password
import re
from goods.models import Merchant, Kinds, Category, Goods
from utils.QiNiuTools import QiniuTool
from utils.Smstools import SmsTool
from utils.JwtTools import JwtTool
from utils.RedisTools import RedisTool


# Create your views here.

# 注册
class Register(APIView):
    def post(self,request):
        # 获取前端提交的数据
        name=request.data.get('name')
        kind_id=request.data.get('kind_id')
        code=request.data.get('code')
        pwd=request.data.get('pwd')
        mobile=request.data.get('mobile')
        print(pwd,mobile,code,kind_id,name)
        # 2.判断信息是否齐全
        if not all([code,pwd,mobile,name,kind_id]):
            return Response({'code':204,'msg':'注册信息不完整'})
        if RedisTool().rds.get('sms_'+mobile).decode()!=code:
            return Response({'code': 400, 'msg': '验证码已过期'})
        # 判断手机号是否存在
        if not re.findall(r'^1[3-9]\d{9}$', mobile):
            return Response({'code': 404, 'msg': '手机号不存在'})
        # 判断手机号是否注册
        if Merchant.objects.filter(mobile=mobile):
            return Response({'code': 400, 'msg': '手机号已注册'})
        if not Kinds.objects.filter(id=kind_id):
            return Response({'code': 400, 'msg': '分类不存在'})
        # 4.往数据库中保存数据
        password=make_password(pwd)
        # print(password)
        Merchant.objects.create(name=name,password=password,mobile=mobile,kind_id=kind_id)
        return Response({'code':200,'msg':'注册成功'})

class SmsCode(APIView):
    def get(self,request,mobile):
        # 校验参数
        rule=r'^1[3-9]\d{9}$'
        if not re.findall(rule,mobile):
            return Response({
                'code':400,
                'msg':'手机号格式不正确'
            })
        # 随机生成6位验证码
        code=random.randint(100000,999999)
        # 存入 redis数据库
        r=RedisTool().rds
        r.set(f'sms_{mobile}',code,ex=5*60)
        r.close()
        res=SmsTool().send_code(mobile,code)
        if not res:
            return Response({'code':400,"msg":'验证码发送失败'})
        return Response({'code':200,"msg":'验证码发送成功'})




class Login(APIView):
    def post(self,request):
        # 1.获取 手机号 密码
        mobile=request.data.get('mobile')
        pwd=request.data.get('password')
        print(mobile,pwd)
        # 2.获取数据库中的数据，判断用户名是否存在
        try:
            mer=Merchant.objects.get(mobile=mobile)
            mer.last_login=datetime.now()
            mer.save()
        except Exception as e:
            print(e)
            return Response({'code':204,'msg':'用户名不存在'})
        # 判断密码是否正确
        # print(mer.password)
        if not check_password(pwd,mer.password):
            return Response({'code':204,'msg':'用户名或密码错误'})
        print(mer)
        token=JwtTool().create_jwt(mer)
        return Response({
            'code':200,
            'token':token,
            'msg':f'欢迎商家{mer.mobile}登录',
        })
    # pbkdf2_sha256$150000$xhIHwxd4US4A$lh0tGUccO2kE2XGGChn/3ZR4OWFOVynjUyKsPokDSik=
    # pbkdf2_sha256$150000$xhIHwxd4US4A$lh0tGUccO2kE2XGGChn/3ZR4OWFOVynjUyKsPokDSik=
class MerchantInfo(APIView):
    def get(self,request):
        # 获取单个商家
        try:
            id = request.user_info.get('id')
            # 1.判断用户是否登录
            mer = Merchant.objects.get(id=id)
        except Exception as e:
            print(e)
            return Response({'msg': '用户不存在或未登录', 'code': '403'})
        cates = []
        for i in mer.category_set.all():
            _goods = []
            for j in i.goods_set.all():
                _goods.append({
                    'id': j.id,
                    'name': j.sku_name,
                    'price': j.price,
                    'img': j.img,
                    'instruction': j.instruction,
                    'sell_price': j.selling_price,
                    'count': j.count,
                    'stock': j.stock,
                })
            cates.append({
                'id': i.id,
                'cate_name': i.cate_name,
                'goods': _goods,
            })
            print(mer.goods_set.values_list('count'))
        return Response({
            'code': 200,
            'msg': '获取商家详情成功',
            'data': {
                'id': mer.id,
                'name': mer.name,
                'avatar': mer.avatar,
                'start_send': mer.start_send,
                'sending': mer.sending,
                'average': mer.average,
                'kind_name':mer.kind.cate_name,
                'sum_num':1,
                'cate':cates
            },
        })
    def post(self,request):
        # 获取单个商家
        try:
            id = request.user_info.get('id')
            # 1.判断用户是否登录
            mer = Merchant.objects.get(id=id)
        except Exception as e:
            print(e)
            return Response({'msg': '用户不存在或未登录', 'code': '403'})

        return Response({
            'code': 200,
            'msg': '获取商家详情成功',
            'data': {
                'id': mer.id,
                'mobile': mer.mobile,
                'name': mer.name,
                'avatar': mer.avatar,
                'start_send': mer.start_send,
                'sending': mer.sending,
                'average': mer.average,
                'kind_id': mer.kind_id,
                'business_time': mer.business_time,
            },
        })
    def put(self,request):
        try:
            id = request.user_info.get('id')
            # 1.判断用户是否登录
            mer = Merchant.objects.get(id=id)
        except Exception as e:
            print(e)
            return Response({'msg': '用户不存在或未登录', 'code': '403'})
        name=request.data.get('name')
        business_time=request.data.get('business_time')
        start_send=request.data.get('start_send')
        sending=request.data.get('sending')
        average=request.data.get('average')
        kind_id=request.data.get('kind_id')
        if not all([name,business_time,start_send,sending,average,kind_id]):
            return Response({'code':'200','msg':'参数错误'})
        try:
            Merchant.objects.filter(id=id).update(
                name=name,
                business_time=business_time,
                start_send=start_send,
                sending=sending,
                average=average,
                kind_id=kind_id,
            )
        except Exception as e:
            print(e)
            return Response({'code':400,'msg':'修改商家信息失败'})
        return Response({'code': 200, 'msg': '修改商家信息成功'})


class Upload(APIView):
    def post(self,request):
        try:
            id = request.user_info.get('id')
            # 1.判断用户是否登录
            mer = Merchant.objects.get(id=id)
        except Exception as e:
            print(e)
            return Response({'msg': '用户不存在或未登录', 'code': '403'})
        #  FILES;获取前端图片
        files=request.FILES.get('file')
        print('>>>>>>>>>>>>',files)
        print('>>>>>>>>>>>>',files.name,files.file)
        # 图片写入位置
        file_dir=settings.STATICFILES_DIRS[1]
        # file_dir='http://127.0.0.1:8000/static/merchant'
        print("图片路径前缀》》》",file_dir)
        # 拼接图片路径
        file_name=file_dir+'/'+files.name
        print('完整图片路径》》》',file_name)
        # 写入指定文件
        with open(file_name,'wb') as f:
            # 读取图片字节流写入文件
            f.write(files.file.read())
        rsp=QiniuTool().upload('merchant/'+files.name)
        if rsp:
            mer.avatar='http://rmd3r0mox.hn-bkt.clouddn.com/'+rsp
            mer.save()
            return Response({
                'code':200,
                'msg':'上传成功',
                'files_path':mer.avatar,
                'files_name':rsp
            })
class CateInfo(APIView):
    def get(self,request):
        try:
            uid = request.user_info.get('id')
            # 1.判断用户是否登录
            mer = Merchant.objects.get(id=uid)
        except Exception as e:
            print('>>>>>',e)
            return Response({'msg': '用户不存在或未登录', 'code': '403'})
        try:
            cates=Category.objects.all()
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '获取商品分类失败'})
        _list=[]
        for i in cates:
            _list.append({
                'id':i.id,
                'cate_name': i.cate_name,
            })
        return Response({
            'code': 200,
            'msg': '获取商品分类成功',
            'data':_list
        })
    def post(self,request):
        try:
            id = request.user_info.get('id')
            # 1.判断用户是否登录
            mer = Merchant.objects.get(id=id)
        except Exception as e:
            print('>>>>>',e)
            return Response({'msg': '用户不存在或未登录', 'code': '403'})
        name=request.data.get('name')
        if not name:
            return Response({'code': 400, 'msg': '参数错误'})
        if Category.objects.filter(cate_name=name):
            return Response({'code': 400, 'msg': '分类已存在'})
        try:
            Category.objects.create(cate_name=name,merchant=mer)
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '添加商品分类失败'})
        return Response({'code': 200, 'msg': '添加商品分类成功'})
class CateView(APIView):
    def get(self,request,id):
        try:
            uid = request.user_info.get('id')
            # 1.判断用户是否登录
            mer = Merchant.objects.get(id=uid)
        except Exception as e:
            print('>>>>>',e)
            return Response({'msg': '用户不存在或未登录', 'code': '403'})
        try:
            cate=Category.objects.get(id=id)
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '获取商品分类失败'})

        return Response({
            'code': 200,
            'msg': '获取商品分类成功',
            'data':{
                'id':cate.id,
                'name':cate.cate_name
            }
        })
    def put(self,request,id):
        try:
            uid = request.user_info.get('id')
            # 1.判断用户是否登录
            mer = Merchant.objects.get(id=uid)
        except Exception as e:
            print('>>>>>',e)
            return Response({'msg': '用户不存在或未登录', 'code': '403'})
        name=request.data.get('name')
        if not name:
            return Response({'code': 400, 'msg': '参数错误'})
        try:
            cate=Category.objects.filter(id=id).update(cate_name=name)
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '修改商品分类失败'})

        return Response({
            'code': 200,
            'msg': '修改商品分类成功',
        })
    def delete(self,request,id):
        try:
            uid = request.user_info.get('id')
            # 1.判断用户是否登录
            mer = Merchant.objects.get(id=uid)
        except Exception as e:
            print('>>>>>',e)
            return Response({'msg': '用户不存在或未登录', 'code': '403'})
        name=request.data.get('name')
        try:
            cate=Category.objects.filter(id=id).delete()
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '删除商品分类失败'})

        return Response({
            'code': 200,
            'msg': '删除商品分类成功',
        })
class GoodsInfo(APIView):
    def get(self,request):
        try:
            uid = request.user_info.get('id')
            # 1.判断用户是否登录
            mer = Merchant.objects.get(id=uid)
        except Exception as e:
            print('>>>>>',e)
            return Response({'msg': '用户不存在或未登录', 'code': '403'})
        try:
            data=Goods.objects.filter(merchant_id=mer.id)
        except Exception as e:
            print(e)
            return Response({'code':400,'msg':'获取所有商品失败'})
        _list=[]
        for i in data:
            _list.append({
                'name': i.sku_name,
                'id': i.id,
                'price': i.price,
                'sell_price': i.selling_price,
                'img': i.img,
                'instruction': i.instruction,
                'count': i.count,
                'stock': i.stock,
                'cate_id': i.cate_id,
                'merchant_id': i.merchant_id,
                'online': i.online,
            })
        return Response({
            'code': 200,
            'msg': '获取所有商品成功',
            'data':_list
        })

    def post(self,request):
        try:
            uid = request.user_info.get('id')
            # 1.判断用户是否登录
            mer = Merchant.objects.get(id=uid)
        except Exception as e:
            print('>>>>>',e)
            return Response({'msg': '用户不存在或未登录', 'code': '403'})

        name=request.data.get('name')
        img=request.data.get('img')
        sell_price=request.data.get('sell_price')
        price=request.data.get('price')
        instruction=request.data.get('instruction')
        stock=request.data.get('stock')
        online=request.data.get('online')
        cate_id=request.data.get('cate_id')
        if not all([name,img,sell_price,price,instruction,cate_id]):
            return Response({'code': 400, 'msg': '参数错误'})

        if not Category.objects.filter(id=cate_id):
            return Response({'code':400,'msg':'商品分类不存在'})

        try:
            if not stock:
                stock=0
            if not online:
                online=False
            else:
                online=True
            good=Goods.objects.create(
                sku_name=name,
                price=price,
                selling_price=sell_price,
                instruction=instruction,
                stock=stock,
                img=img,
                online=online,
                cate_id=cate_id,
                merchant=mer,
            )

        except Exception as e:
            print(e)
            return Response({'code':400,'msg':'添加商品失败'})
        return Response({'code':200,'msg':'添加商品成功'})
class GoodsView(APIView):
    def get(self,request,id):
        try:
            uid = request.user_info.get('id')
            # 1.判断用户是否登录
            mer = Merchant.objects.get(id=uid)
        except Exception as e:
            print('>>>>>',e)
            return Response({'msg': '用户不存在或未登录', 'code': '403'})
        try:
            good=Goods.objects.get(id=id)
        except Exception as e:
            print(e)
            return Response({'code':400,'msg':'获取单个商品失败'})

        return Response({
            'code':200,
            'msg':'获取单个商品成功',
            'data':{
                'name':good.sku_name,
                'id':good.id,
                'price': good.price,
                'sell_price': good.selling_price,
                'img': good.img,
                'instruction': good.instruction,
                'count': good.count,
                'stock': good.stock,
                'cate_id': good.cate_id,
                'merchant_id': good.merchant_id,
                'online': good.online,
            }
        })


    def put(self,request,id):
        try:
            uid = request.user_info.get('id')
            # 1.判断用户是否登录
            mer = Merchant.objects.get(id=uid)
        except Exception as e:
            print('>>>>>',e)
            return Response({'msg': '用户不存在或未登录', 'code': '403'})

        name=request.data.get('name')
        img=request.data.get('img')
        sell_price=request.data.get('sell_price')
        price=request.data.get('price')
        instruction=request.data.get('instruction')
        stock=request.data.get('stock')
        online=request.data.get('online')
        cate_id=request.data.get('cate_id')
        if not all([name,img,sell_price,price,instruction,cate_id]):
            return Response({'code': 400, 'msg': '参数错误'})

        if not Category.objects.filter(id=cate_id):
            return Response({'code':400,'msg':'商品分类不存在'})

        try:
            if not online:
                online=False
            else:
                online=True
            print(online)
            Goods.objects.filter(id=id).update(
                sku_name=name,
                price=price,
                selling_price=sell_price,
                instruction=instruction,
                stock=stock,
                img=img,
                online=online,
                cate_id=cate_id,
            )
        except Exception as e:
            print(e)
            return Response({'code':400,'msg':'修改商品失败'})
        return Response({'code':200,'msg':'修改商品成功'})
    def delete(self,request,id):
        try:
            uid = request.user_info.get('id')
            # 1.判断用户是否登录
            mer = Merchant.objects.get(id=uid)
        except Exception as e:
            print('>>>>>',e)
            return Response({'msg': '用户不存在或未登录', 'code': '403'})
        if not Goods.objects.filter(id=id):
            return Response({'code':400,'msg':'商品不存在'})
        try:
            Goods.objects.filter(id=id).delete()
        except Exception as e:
            print(e)
            return Response({'code':400,'msg':'删除商品失败'})
        return Response({'code': 200, 'msg': '删除商品成功'})



